package com.itstyle.quartz.service.impl;

import com.itstyle.quartz.entity.Auth;
import com.itstyle.quartz.mapper.AuthMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张霄峰
 * @email 29839415@qq.com
 * @date 2020/4/14 13:22
 */
@Service
public class AuthService implements UserDetailsService {
    @Autowired
    AuthMapper autmapper;

    public List<Auth> finall(){
        return autmapper.finall();
    }

    public Auth getuser( String username,  String password){
        return autmapper.getuser(username, password);
    }

    /**
     * 安全认证 实现 UserDetailsService 接口的方法实现
     * 根据用户的 username 来加载用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据 username 查询出用户信息
        Auth auth = autmapper.byusername(username);

        if(auth == null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String newPassword = passwordEncoder.encode(auth.getPassword());//加密
        System.out.println("加密密码：" + newPassword);

        return new User(auth.getUsername(),newPassword,createAuthority(auth.getAut()));

    }

    //这里是将数据库的角色分割，构造GrantedAuthority
    private List<SimpleGrantedAuthority> createAuthority(String roles) {
        String[] roleArray = roles.split(",");
        List<SimpleGrantedAuthority> authorityList = new ArrayList<SimpleGrantedAuthority>();
        for (String role : roleArray) {
            authorityList.add(new SimpleGrantedAuthority(role));
        }
        return authorityList;
    }
}
